import java.awt.Color;
import java.awt.Dimension;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

//TODO: Sort columns

public class PatientExplorer extends JInternalFrame implements DocumentListener {
	
	private static final int STARTING_PATIENT_NUM = 1000;
	
	public JButton viewPatientButton, addPatientButton, archivePatientButton, checkinPatientButton;
	
	public JTable patientTable;
	private String[] columnNames = {"CHRID", "Last Name", "First Name", "Phone"};
	private JScrollPane patientTableScroll;
	
	private JTextField searchField;
	
	public Patient[] patients;
	
	public PatientExplorer() {
		super("Patients");
		 setBounds(50, 50, 555, 500);
	     setVisible(true);
	     //getContentPane().setLayout(null);
	     setLayout( new BoxLayout( getContentPane(), BoxLayout.X_AXIS ) );
	     setResizable(true);
	     setFrameIcon(null);
	     setClosable(true);
	     toFront();
	     
	     patientTable = new JTable();
	     DefaultTableModel tableModel = new DefaultTableModel(columnNames,0);
	     patientTable = new JTable(tableModel);
	     patientTable.setPreferredScrollableViewportSize(new Dimension(400, 400));
	     patientTableScroll = new JScrollPane(patientTable);
	     patientTable.setSelectionForeground( Color.white );
	     patientTable.setSelectionBackground( new Color(184, 207, 229, 255) );
	     patientTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);	        

	     JPanel leftPanel = new JPanel();
	     leftPanel.setBorder( BorderFactory.createEmptyBorder(10, 10, 10, 5) );
	     leftPanel.setLayout( new BoxLayout( leftPanel, BoxLayout.Y_AXIS ) );
	     leftPanel.add( patientTableScroll );
	     
	     leftPanel.add(Box.createRigidArea(new Dimension(0,5)));

	     
	     searchField = new JTextField(42);
	     searchField.setMaximumSize( new Dimension(1000,25) );
	     searchField.getDocument().addDocumentListener(this);
	     leftPanel.add( searchField );

	     JPanel rightPanel = new JPanel();
	     rightPanel.setMaximumSize( new Dimension(150, 1000) );
	     
	     
	     JPanel buttonsPanel = new JPanel();
	     buttonsPanel.setLayout( new BoxLayout(buttonsPanel, BoxLayout.Y_AXIS) );

	     viewPatientButton = new JButton("Patient Details");
	     buttonsPanel.add( viewPatientButton );
	     addPatientButton = new JButton("  Add Patient  ");
	     buttonsPanel.add( addPatientButton );
	     archivePatientButton = new JButton("Archive Patient");
	     buttonsPanel.add( archivePatientButton );
	     checkinPatientButton = new JButton("    Check-in    ");
	     buttonsPanel.add( checkinPatientButton );
	    
	     rightPanel.add(buttonsPanel);

	     getContentPane().add(leftPanel);
	     getContentPane().add(rightPanel);

	     //setup dummy patients
	     patients = new Patient[3];

	     patients[0] = new Patient( STARTING_PATIENT_NUM, "Wong", "Jeffrey");
	     patients[0].setPhone("14039114567");

	     patients[1] = new Patient( STARTING_PATIENT_NUM + 1, "Saba", "Dori");
	     patients[1].setMiddleName("John");
	     patients[1].setAddress("123 Elbow Drive NE");
	     patients[1].setSex('M');
	     patients[1].setHeight(173);
	     patients[1].setWeight(110);
	     patients[1].setBloodType("B+");
	     patients[1].setPostalCode("T2B1M5");
	     patients[1].setPhone("14039182837");
	     patients[1].setCity("Calgary");
	     patients[1].setProvState("Alberta");
	     patients[1].setCountry("Canada");
	     patients[1].setEmergencyFirstName("Samir");
	     patients[1].setEmergencyLastName("Chokshi");
	     patients[1].setEmergencyPhone("14031584659");
	     String des0 = "Dori may have an allergic reaction\nIt is difficult to tell at this time exactly what it was\n\nPrescribed:Soft Soap";
	     patients[1].addMedicalVisit( new Date(2007,11,05), "Dr. Ronald Osprey", des0);
	     String des1 = "Area of interest seems to be better.";
	     patients[1].addMedicalVisit( new Date(2008,02,11), "Dr. Ozzie Watkins", des1);
	     String des2 = "A clear cut impedement in the anterior lobe.\nRecommending a bone density scan to determine possible cause";
	     patients[1].addMedicalImage(new Date(2007,11,05), "MRI", System.getProperty("user.dir") + "/MRIhead/", des2);
	     patients[1].addMedicalCondition("Allergy", "Outdoor allergies.\nAllergies flare up during spring.");
	     patients[1].addMedicalCondition("Asthma", "Difficulty in playing basketball.\nTakes puffer twice a day");
	     patients[1].addMedication( "Claritin Extra Strength", "Dr. Elle Tessa", "", true);
	     patients[1].addMedication( "Centro", "Dr. Max Droople", "May require double dose", false);
	     
	     patients[2] = new Patient( STARTING_PATIENT_NUM + 2, "Sabhaney", "Ajay" );
	     patients[2].setPhone("14036891109");
	     
	     
	     fillTableWithAllPatients();
	}
	
	private void fillTableWithAllPatients() {
		patientTable.setModel( new DefaultTableModel(columnNames, 0) );
		for( int i = 0; i < patients.length; i++ ) {
	    	 addPatientToTable( patients[i] );
	     }
	}
	
	private void addPatientToTable( Patient p ) {
		String[] rowData = { String.valueOf( p.getId() ), p.getLastName(), p.getFirstName(), p.getPhone() };
		tableModel().addRow( rowData );
	}
	
	//search stuff
	public void changedUpdate( DocumentEvent evt ) {
		autosearch();
	}
	public void insertUpdate( DocumentEvent evt ) {
		autosearch();
	}
	public void removeUpdate( DocumentEvent evty) {
		autosearch();
	}
	
	private void autosearch() {
		String searchCriteria = searchField.getText().trim();
		
		if ( searchCriteria.equals("") ) {
			fillTableWithAllPatients();
		}
		else {
			DefaultTableModel model = new DefaultTableModel(columnNames, 0);
			for( int i = 0; i < patients.length; i++ ) {
				if ( patients[i].search(searchCriteria) ) {
					Patient p = patients[i];
					String[] rowData = { String.valueOf( p.getId() ), p.getLastName(), p.getFirstName(), p.getPhone() };
					model.addRow(rowData);
				}
			}
			patientTable.setModel( model );
		}
	}
	
	
	
	
	public Patient getPatientFromTable( int row ) {
		int id = Integer.parseInt( String.valueOf( tableModel().getValueAt(row, 0) ) );
		for ( int i = 0; i < patients.length; i++ ) {
			if( patients[i].getId() == id ) {
				return patients[i];
			}
		}
		
		return null;
	}
	
	public DefaultTableModel tableModel() {
		return (DefaultTableModel)(patientTable.getModel());
	}

	public Patient getPatientFromFirstName(String text) {
		for( int i = 0; i < patientTable.getRowCount(); i++ ) {
			String fN = String.valueOf( tableModel().getValueAt(i, 2) );
			if ( fN.equals(text) ) {
				int id = Integer.parseInt( String.valueOf( tableModel().getValueAt(i, 0) ) );
				for ( int j = 0; j < patients.length; j++ ) {
					if( patients[j].getId() == id ) {
						return patients[j];
					}
				}
			}
		}
		
		return null;
	}
	
}
